﻿using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.PB;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Coldairarrow.Business.PB
{
    public partial class PB_ReturnSortingBusiness : BaseBusiness<PB_ReturnSorting>, IPB_ReturnSortingBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public PB_ReturnSortingBusiness(IDbAccessor db, IOperator @operator)
            : base(db)
        {
            _operator = @operator;
        }

        #region 外部接口

        public async Task<PageResult<PB_ReturnSorting>> GetDataListAsync(PageInput<ConditionDTO> input)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<PB_ReturnSorting>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<PB_ReturnSorting, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<PB_ReturnSorting> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(PB_ReturnSorting data)
        {
            await InsertAsync(data);
        }

        public async Task UpdateDataAsync(PB_ReturnSorting data)
        {
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            await DeleteAsync(ids);
        }

        /// <summary>
        /// 获取分拣数据列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageResult<PB_ReturnSortingDto>> GetReturnSortingListAsync(PageInput<ConditionDTO> input)
        {
            var search = input.Search;
            Expression<Func<PB_ReturnSorting, PB_Project, Base_Department, PB_ReturnSortingDto>> select = (a, b, c) => new PB_ReturnSortingDto
            {
                ProjectName = b.Name,
                DeptName=c.Name,
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ReturnSorting>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);

            return await q.GetPageResultAsync(input);
        }
        /// <summary>
        /// PDA回货分拣提交时生成 分拣表数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task AddDataListAsync(PB_ReturnSortingList data)
        {
            Base_User RellName = await Db.GetIQueryable<Base_User>().Where(m => m.Id == _operator.UserId).FirstOrDefaultAsync();
            String ReturnSortingId = IdHelper.GetId();
            PB_ReturnSorting pB_ReturnSorting = new PB_ReturnSorting();
            pB_ReturnSorting.Id = ReturnSortingId;
            pB_ReturnSorting.ParentId = data.ParentId;
            pB_ReturnSorting.ProjectId = data.ProjectId;
            pB_ReturnSorting.ReturnDate = data.ReturnDate;
            pB_ReturnSorting.Consignee = data.Consignee;
            pB_ReturnSorting.State = 0;
            pB_ReturnSorting.CreatorId = RellName.Id;
            pB_ReturnSorting.CreatorRealName = RellName.RealName;
            pB_ReturnSorting.CreateTime = DateTime.Now;
            pB_ReturnSorting.Deleted = false;
            pB_ReturnSorting.DetpId = RellName.DepartmentId;
            pB_ReturnSorting.StorId = data.StorId;
            await InsertAsync(pB_ReturnSorting);
            List<PB_ReturnSortDetail> pB_ReturnSortDetails = new List<PB_ReturnSortDetail>();
            if (data.Subdata.Count>0) {
                foreach (var item in data.Subdata) {
                    string SubId = IdHelper.GetId();
                    PB_ReturnSortDetail pB_ReturnSortDetail = new PB_ReturnSortDetail();
                    pB_ReturnSortDetail.Id = SubId;
                    pB_ReturnSortDetail.ParentId = ReturnSortingId;
                    pB_ReturnSortDetail.ProjectId = data.ProjectId;
                    pB_ReturnSortDetail.MaterialId = item.MaterialId;
                    pB_ReturnSortDetail.DeliverNums = item.DeliverNums;
                    pB_ReturnSortDetail.SortingSum = item.SortingSum;
                    pB_ReturnSortDetail.ReturnNums = item.ReturnNums;
                    pB_ReturnSortDetail.CreateTime = DateTime.Now;
                    pB_ReturnSortDetail.CreatorRealName = RellName.RealName;
                    pB_ReturnSortDetail.CreatorId = RellName.Id;
                    pB_ReturnSortDetail.Deleted = false;
                    pB_ReturnSortDetails.Add(pB_ReturnSortDetail);

                    string sql = "UPDATE PB_ReturnDetailLog  set SortingSum=SortingSum+" + item.SortingSum + " WHERE ParentId='" + data.ParentId+ "'  and  ProjectId='"+item.ProjectId+ "'  AND   MaterialId ='"+item.MaterialId+"'";
                    await ExecuteSqlAsync(sql);
                }
                await Db.InsertAsync<PB_ReturnSortDetail>(pB_ReturnSortDetails);
            } 

        }
        /// <summary>
        /// 分拣单 编辑/查看/审核接口
        /// </summary>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public async Task<PB_ReturnSortingListInfo> GetListInfo(string ParentId)
        {
            
            Expression<Func<PB_ReturnSorting, PB_Project, Base_Department, PB_ReturnSortingListInfo>> select = (a, b, c) => new PB_ReturnSortingListInfo
            {
                ProjectName = b.Name,
                DeptName = c.Name,
               
            };
            select = select.BuildExtendSelectExpre();
            var q = from a in Db.GetIQueryable<PB_ReturnSorting>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<Base_Department>() on a.Consignee equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @select.Invoke(a, b, c);
            PB_ReturnSortingListInfo Data = await q.Where(m=>m.Id==ParentId).FirstOrDefaultAsync();
            Expression<Func<PB_ReturnSortDetail, PB_Project, PB_Material, PB_ReturnSortDetailDTO>> selects = (a, b, c) => new PB_ReturnSortDetailDTO
            {
               
                MaterialName = c.Name,
                MaterialCode=c.Code,
                MateralSpec=c.Spec,
                Price=c.Price,
                Amount=c.Price*a.SortingSum, 
            };
            selects = selects.BuildExtendSelectExpre();
            var qs = from a in Db.GetIQueryable<PB_ReturnSortDetail>().AsExpandable()
                    join b in Db.GetIQueryable<PB_Project>() on a.ProjectId equals b.Id into ab
                    from b in ab.DefaultIfEmpty()
                    join c in Db.GetIQueryable<PB_Material>() on a.MaterialId equals c.Id into ac
                    from c in ac.DefaultIfEmpty()
                    select @selects.Invoke(a, b, c);
            List<PB_ReturnSortDetailDTO> Sub =await qs.Where(m=>m.ParentId==ParentId).ToListAsync();
            PB_ReturnSortingListInfo LIST = new PB_ReturnSortingListInfo();
            LIST.Id = Data.Id;
            LIST.ParentId = Data.ParentId;
            LIST.ProjectName = Data.ProjectName;
            LIST.DeptName = Data.DeptName;
            LIST.ProjectId = Data.ProjectId;
            LIST.DetpId = Data.DetpId;
            LIST.ReturnDate = Data.ReturnDate;
            LIST.Consignee = Data.Consignee;
            LIST.State = Data.State;
            LIST.StorId = Data.StorId;
            LIST.Subdata = Sub;
            LIST.CreateTime = Data.CreateTime;
            return LIST;

        }
        public async Task UpdataState(string Id)
        {
            string sql = "UPDATE PB_ReturnSorting  set State=1 WHERE Id='" + Id + "' ";
            await ExecuteSqlAsync(sql);

        }
        /// <summary>
        /// PDA提交回货通知创建装车单明细
        /// </summary>
        /// <param name="Data"></param>
        /// <returns></returns>
        public async Task ReturnTransportBillDetailAdd(ReturnTransportBillDetailAdd Data)
        {
            Base_User RellName = await Db.GetIQueryable<Base_User>().Where(m => m.Id == _operator.UserId).FirstOrDefaultAsync();
            List<PB_TransportBillDetail> SubData = new List<PB_TransportBillDetail>();
            foreach (var item in Data.Details) {
                string subid = IdHelper.GetId();
                PB_TransportBillDetail  Model= new PB_TransportBillDetail();
                Model.Id = subid;
                Model.ParentId = Data.TransportBillId;
                Model.DesignDetailId = "";
                Model.PreparationNoteId = "";
                Model.PackId = "";
                Model.MaterialId = item.MaterialId;
                Model.PretendCarUserId = "";
                Model.PretendCarUserName = "";
                Model.PretendCarTime = DateTime.Now;
                Model.PackNums = item.ReceiptQuantity;
                Model.ReceiptQuantity = item.ReceiptQuantity;
                Model.CreatorId = RellName.Id;
                Model.CreatorName = RellName.RealName;
                Model.CreateTime = DateTime.Now;
                Model.Deleted = false;
                Model.Status = 0;
                SubData.Add(Model);
            }
            await Db.InsertAsync<PB_TransportBillDetail>(SubData);
        }

        #endregion

        #region 私有成员

        #endregion
    }
}